<?php

/**
 * 
 *
 * @version 1.107
 * @package entity
 */
class AlaniaContenidosModel extends Db2PhpEntityBase implements Db2PhpEntityModificationTracking {

    private static $CLASS_NAME = 'AlaniaContenidosModel';

    const SQL_IDENTIFIER_QUOTE = '`';
    const SQL_TABLE_NAME = 'alania_contenidos';
    const SQL_INSERT = 'INSERT INTO `alania_contenidos` (`id`,`nombre`,`plantilla`,`alania_tipo_informacion_id_tipo_informacion`,`fecha_creacion`,`fecha_modificacion`) VALUES (?,?,?,?,?,?)';
    const SQL_INSERT_AUTOINCREMENT = 'INSERT INTO `alania_contenidos` (`nombre`,`plantilla`,`alania_tipo_informacion_id_tipo_informacion`,`fecha_creacion`,`fecha_modificacion`) VALUES (?,?,?,?,?)';
    const SQL_UPDATE = 'UPDATE `alania_contenidos` SET `id`=?,`nombre`=?,`plantilla`=?,`alania_tipo_informacion_id_tipo_informacion`=?,`fecha_creacion`=?,`fecha_modificacion`=? WHERE `id`=?';
    const SQL_SELECT_PK = 'SELECT * FROM `alania_contenidos` WHERE `id`=?';
    const SQL_SELECT_NAME = 'SELECT * FROM `alania_contenidos` WHERE `nombre`=?';
    const SQL_DELETE_PK = 'DELETE FROM `alania_contenidos` WHERE `id`=?';
    const FIELD_ID = -769648608;
    const FIELD_NOMBRE = 527257678;
    const FIELD_PLANTILLA = -1129807842;
    const FIELD_ALANIA_TIPO_INFORMACION_ID_TIPO_INFORMACION = -18463661;
    const FIELD_FECHA_CREACION = 2085938839;
    const FIELD_FECHA_MODIFICACION = 1115614676;

    private static $PRIMARY_KEYS = array(self::FIELD_ID);
    private static $AUTOINCREMENT_FIELDS = array(self::FIELD_ID);
    private static $FIELD_NAMES = array(
        self::FIELD_ID => 'id',
        self::FIELD_NOMBRE => 'nombre',
        self::FIELD_PLANTILLA => 'plantilla',
        self::FIELD_ALANIA_TIPO_INFORMACION_ID_TIPO_INFORMACION => 'alania_tipo_informacion_id_tipo_informacion',
        self::FIELD_FECHA_CREACION => 'fecha_creacion',
        self::FIELD_FECHA_MODIFICACION => 'fecha_modificacion');
    private static $PROPERTY_NAMES = array(
        self::FIELD_ID => 'id',
        self::FIELD_NOMBRE => 'nombre',
        self::FIELD_PLANTILLA => 'plantilla',
        self::FIELD_ALANIA_TIPO_INFORMACION_ID_TIPO_INFORMACION => 'alaniaTipoInformacionIdTipoInformacion',
        self::FIELD_FECHA_CREACION => 'fechaCreacion',
        self::FIELD_FECHA_MODIFICACION => 'fechaModificacion');
    private static $PROPERTY_TYPES = array(
        self::FIELD_ID => Db2PhpEntity::PHP_TYPE_INT,
        self::FIELD_NOMBRE => Db2PhpEntity::PHP_TYPE_STRING,
        self::FIELD_PLANTILLA => Db2PhpEntity::PHP_TYPE_STRING,
        self::FIELD_ALANIA_TIPO_INFORMACION_ID_TIPO_INFORMACION => Db2PhpEntity::PHP_TYPE_INT,
        self::FIELD_FECHA_CREACION => Db2PhpEntity::PHP_TYPE_STRING,
        self::FIELD_FECHA_MODIFICACION => Db2PhpEntity::PHP_TYPE_STRING);
    private static $FIELD_TYPES = array(
        self::FIELD_ID => array(Db2PhpEntity::JDBC_TYPE_INTEGER, 10, 0, false),
        self::FIELD_NOMBRE => array(Db2PhpEntity::JDBC_TYPE_VARCHAR, 45, 0, false),
        self::FIELD_PLANTILLA => array(Db2PhpEntity::JDBC_TYPE_LONGVARCHAR, 65535, 0, false),
        self::FIELD_ALANIA_TIPO_INFORMACION_ID_TIPO_INFORMACION => array(Db2PhpEntity::JDBC_TYPE_INTEGER, 10, 0, false),
        self::FIELD_FECHA_CREACION => array(Db2PhpEntity::JDBC_TYPE_TIMESTAMP, 19, 0, true),
        self::FIELD_FECHA_MODIFICACION => array(Db2PhpEntity::JDBC_TYPE_TIMESTAMP, 19, 0, true));
    private static $DEFAULT_VALUES = array(
        self::FIELD_ID => null,
        self::FIELD_NOMBRE => '',
        self::FIELD_PLANTILLA => '',
        self::FIELD_ALANIA_TIPO_INFORMACION_ID_TIPO_INFORMACION => 0,
        self::FIELD_FECHA_CREACION => 'CURRENT_TIMESTAMP',
        self::FIELD_FECHA_MODIFICACION => null);
    private $id;
    private $nombre;
    private $plantilla;
    private $alaniaTipoInformacionIdTipoInformacion;
    private $fechaCreacion;
    private $fechaModificacion;

    /**
     * set value for id 
     *
     * type:INT,size:10,default:null,primary,unique,autoincrement
     *
     * @param mixed $id
     * @return AlaniaContenidosModel
     */
    public function &setId($id) {
        $this->notifyChanged(self::FIELD_ID, $this->id, $id);
        $this->id = $id;
        return $this;
    }

    /**
     * get value for id 
     *
     * type:INT,size:10,default:null,primary,unique,autoincrement
     *
     * @return mixed
     */
    public function getId() {
        return $this->id;
    }

    /**
     * set value for nombre 
     *
     * type:VARCHAR,size:45,default:null,unique
     *
     * @param mixed $nombre
     * @return AlaniaContenidosModel
     */
    public function &setNombre($nombre) {
        $this->notifyChanged(self::FIELD_NOMBRE, $this->nombre, $nombre);
        $this->nombre = $nombre;
        return $this;
    }

    /**
     * get value for nombre 
     *
     * type:VARCHAR,size:45,default:null,unique
     *
     * @return mixed
     */
    public function getNombre() {
        return $this->nombre;
    }

    /**
     * set value for plantilla 
     *
     * type:TEXT,size:65535,default:null
     *
     * @param mixed $plantilla
     * @return AlaniaContenidosModel
     */
    public function &setPlantilla($plantilla) {
        $this->notifyChanged(self::FIELD_PLANTILLA, $this->plantilla, $plantilla);
        $this->plantilla = $plantilla;
        return $this;
    }

    /**
     * get value for plantilla 
     *
     * type:TEXT,size:65535,default:null
     *
     * @return mixed
     */
    public function getPlantilla() {
        return $this->plantilla;
    }

    /**
     * set value for alania_tipo_informacion_id_tipo_informacion 
     *
     * type:INT,size:10,default:null,index
     *
     * @param mixed $alaniaTipoInformacionIdTipoInformacion
     * @return AlaniaContenidosModel
     */
    public function &setAlaniaTipoInformacionIdTipoInformacion($alaniaTipoInformacionIdTipoInformacion) {
        $this->notifyChanged(self::FIELD_ALANIA_TIPO_INFORMACION_ID_TIPO_INFORMACION, $this->alaniaTipoInformacionIdTipoInformacion, $alaniaTipoInformacionIdTipoInformacion);
        $this->alaniaTipoInformacionIdTipoInformacion = $alaniaTipoInformacionIdTipoInformacion;
        return $this;
    }

    /**
     * get value for alania_tipo_informacion_id_tipo_informacion 
     *
     * type:INT,size:10,default:null,index
     *
     * @return mixed
     */
    public function getAlaniaTipoInformacionIdTipoInformacion() {
        return $this->alaniaTipoInformacionIdTipoInformacion;
    }

    /**
     * set value for fecha_creacion 
     *
     * type:TIMESTAMP,size:19,default:CURRENT_TIMESTAMP,nullable
     *
     * @param mixed $fechaCreacion
     * @return AlaniaContenidosModel
     */
    public function &setFechaCreacion($fechaCreacion) {
        $this->notifyChanged(self::FIELD_FECHA_CREACION, $this->fechaCreacion, $fechaCreacion);
        $this->fechaCreacion = $fechaCreacion;
        return $this;
    }

    /**
     * get value for fecha_creacion 
     *
     * type:TIMESTAMP,size:19,default:CURRENT_TIMESTAMP,nullable
     *
     * @return mixed
     */
    public function getFechaCreacion() {
        return $this->fechaCreacion;
    }

    /**
     * set value for fecha_modificacion 
     *
     * type:TIMESTAMP,size:19,default:null,nullable
     *
     * @param mixed $fechaModificacion
     * @return AlaniaContenidosModel
     */
    public function &setFechaModificacion($fechaModificacion) {
        $this->notifyChanged(self::FIELD_FECHA_MODIFICACION, $this->fechaModificacion, $fechaModificacion);
        $this->fechaModificacion = $fechaModificacion;
        return $this;
    }

    /**
     * get value for fecha_modificacion 
     *
     * type:TIMESTAMP,size:19,default:null,nullable
     *
     * @return mixed
     */
    public function getFechaModificacion() {
        return $this->fechaModificacion;
    }

    /**
     * Get table name
     *
     * @return string
     */
    public static function getTableName() {
        return self::SQL_TABLE_NAME;
    }

    /**
     * Get array with field id as index and field name as value
     *
     * @return array
     */
    public static function getFieldNames() {
        return self::$FIELD_NAMES;
    }

    /**
     * Get array with field id as index and property name as value
     *
     * @return array
     */
    public static function getPropertyNames() {
        return self::$PROPERTY_NAMES;
    }

    /**
     * get the field name for the passed field id.
     *
     * @param int $fieldId
     * @param bool $fullyQualifiedName true if field name should be qualified by table name
     * @return string field name for the passed field id, null if the field doesn't exist
     */
    public static function getFieldNameByFieldId($fieldId, $fullyQualifiedName = true) {
        if (!array_key_exists($fieldId, self::$FIELD_NAMES)) {
            return null;
        }
        $fieldName = self::SQL_IDENTIFIER_QUOTE . self::$FIELD_NAMES[$fieldId] . self::SQL_IDENTIFIER_QUOTE;
        if ($fullyQualifiedName) {
            return self::SQL_IDENTIFIER_QUOTE . self::SQL_TABLE_NAME . self::SQL_IDENTIFIER_QUOTE . '.' . $fieldName;
        }
        return $fieldName;
    }

    /**
     * Get array with field ids of identifiers
     *
     * @return array
     */
    public static function getIdentifierFields() {
        return self::$PRIMARY_KEYS;
    }

    /**
     * Get array with field ids of autoincrement fields
     *
     * @return array
     */
    public static function getAutoincrementFields() {
        return self::$AUTOINCREMENT_FIELDS;
    }

    /**
     * Get array with field id as index and property type as value
     *
     * @return array
     */
    public static function getPropertyTypes() {
        return self::$PROPERTY_TYPES;
    }

    /**
     * Get array with field id as index and field type as value
     *
     * @return array
     */
    public static function getFieldTypes() {
        return self::$FIELD_TYPES;
    }

    /**
     * Assign default values according to table
     * 
     */
    public function assignDefaultValues() {
        $this->assignByArray(self::$DEFAULT_VALUES);
    }

    /**
     * return hash with the field name as index and the field value as value.
     *
     * @return array
     */
    public function toHash() {
        $array = $this->toArray();
        $hash = array();
        foreach ($array as $fieldId => $value) {
            $hash[self::$FIELD_NAMES[$fieldId]] = $value;
        }
        return $hash;
    }

    /**
     * return array with the field id as index and the field value as value.
     *
     * @return array
     */
    public function toArray() {
        return array(
            self::FIELD_ID => $this->getId(),
            self::FIELD_NOMBRE => $this->getNombre(),
            self::FIELD_PLANTILLA => $this->getPlantilla(),
            self::FIELD_ALANIA_TIPO_INFORMACION_ID_TIPO_INFORMACION => $this->getAlaniaTipoInformacionIdTipoInformacion(),
            self::FIELD_FECHA_CREACION => $this->getFechaCreacion(),
            self::FIELD_FECHA_MODIFICACION => $this->getFechaModificacion());
    }

    /**
     * return array with the field id as index and the field value as value for the identifier fields.
     *
     * @return array
     */
    public function getPrimaryKeyValues() {
        return array(
            self::FIELD_ID => $this->getId());
    }

    /**
     * cached statements
     *
     * @var array<string,array<string,PDOStatement>>
     */
    private static $stmts = array();
    private static $cacheStatements = true;

    /**
     * prepare passed string as statement or return cached if enabled and available
     *
     * @param PDO $db
     * @param string $statement
     * @return PDOStatement
     */
    protected static function prepareStatement(PDO $db, $statement) {
        if (self::isCacheStatements()) {
            if (in_array($statement, array(self::SQL_INSERT, self::SQL_INSERT_AUTOINCREMENT, self::SQL_UPDATE, self::SQL_SELECT_PK, self::SQL_DELETE_PK))) {
                $dbInstanceId = spl_object_hash($db);
                if (empty(self::$stmts[$statement][$dbInstanceId])) {
                    self::$stmts[$statement][$dbInstanceId] = $db->prepare($statement);
                }
                return self::$stmts[$statement][$dbInstanceId];
            }
        }
        return $db->prepare($statement);
    }

    /**
     * Enable statement cache
     *
     * @param bool $cache
     */
    public static function setCacheStatements($cache) {
        self::$cacheStatements = true == $cache;
    }

    /**
     * Check if statement cache is enabled
     *
     * @return bool
     */
    public static function isCacheStatements() {
        return self::$cacheStatements;
    }

    /**
     * check if this instance exists in the database
     *
     * @param PDO $db
     * @return bool
     */
    public function existsInDatabase(PDO $db) {
        $filter = array();
        foreach ($this->getPrimaryKeyValues() as $fieldId => $value) {
            $filter[] = new DFC($fieldId, $value, DFC::EXACT_NULLSAFE);
        }
        ;
        /*$firephp=  FirePHP::getInstance(true);
        $firephp->log($this);
        $exampleValues = $this->toArray();
        $filter = array();
        foreach ($exampleValues as $fieldId => $value) {
            if (null !== $value) {
                $filter[$fieldId] = $value;
            }
        }
        $firephp->log($filter);
        //return self::findByFilter($db, $filter, $and, $sort);*/
        $firephp=  FirePHP::getInstance(true);
        $firephp->log($this);
        $firephp->log($filter);
        return 0 != count(self::findByFilter($db, $filter, true));
    }
    
    /**
     * Update to database if exists, otherwise insert
     *
     * @param PDO $db
     * @return mixed
     */
    public function updateInsertToDatabase(PDO $db) {
        if ($this->existsInDatabase($db)) {
            return $this->updateToDatabase($db);
        } else {
            return $this->insertIntoDatabase($db);
        }
    }

    /**
     * Query by Example.
     *
     * Match by attributes of passed example instance and return matched rows as an array of AlaniaContenidosModel instances
     *
     * @param PDO $db a PDO Database instance
     * @param AlaniaContenidosModel $example an example instance defining the conditions. All non-null properties will be considered a constraint, null values will be ignored.
     * @param boolean $and true if conditions should be and'ed, false if they should be or'ed
     * @param array $sort array of DSC instances
     * @return AlaniaContenidosModel[]
     */
    public static function selectAll(PDO $db) {
        return self::findAll($db); //, $filter, $and, $sort);
    }

    public static function findByExample(PDO $db, AlaniaContenidosModel $example, $and = true, $sort = null) {
        $exampleValues = $example->toArray();
        $filter = array();
        foreach ($exampleValues as $fieldId => $value) {
            if (null !== $value) {
                $filter[$fieldId] = $value;
            }
        }
        return self::findByFilter($db, $filter, $and, $sort);
    }

    /**
     * Query by filter.
     *
     * The filter can be either an hash with the field id as index and the value as filter value,
     * or a array of DFC instances.
     *
     * Will return matched rows as an array of AlaniaContenidosModel instances.
     *
     * @param PDO $db a PDO Database instance
     * @param array $filter array of DFC instances defining the conditions
     * @param boolean $and true if conditions should be and'ed, false if they should be or'ed
     * @param array $sort array of DSC instances
     * @return AlaniaContenidosModel[]
     */
    public static function findAll(PDO $db) {
        //if (!($filter instanceof DFCInterface)) {
            //$filter = new DFCAggregate($filter, $and);
        //}
        $filter = array();
        $sql = 'SELECT * FROM `alania_contenidos`';
               // . //self::buildSqlWhere($filter, $and, false, true)
                //. self::buildSqlOrderBy($sort);
 
        $stmt = self::prepareStatement($db, $sql);
        //  self::bindValuesForFilter($stmt, $filter);
        
        return self::fromStatement($stmt);
    }
    public static function findByFilter(PDO $db, $filter, $and = true, $sort = null) {
        if (!($filter instanceof DFCInterface)) {
            $filter = new DFCAggregate($filter, $and);
        }
        $sql = 'SELECT * FROM `alania_contenidos`'
                . self::buildSqlWhere($filter, $and, false, true)
                . self::buildSqlOrderBy($sort);

        $stmt = self::prepareStatement($db, $sql);
        self::bindValuesForFilter($stmt, $filter);
        return self::fromStatement($stmt);
    }

    /**
     * Will execute the passed statement and return the result as an array of AlaniaContenidosModel instances
     *
     * @param PDOStatement $stmt
     * @return AlaniaContenidosModel[]
     */
    public static function fromStatement(PDOStatement $stmt) {
        $firephp=  FirePHP::getInstance(true);
        $firephp->log($stmt);
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        return self::fromExecutedStatement($stmt);
    }

    /**
     * returns the result as an array of AlaniaContenidosModel instances without executing the passed statement
     *
     * @param PDOStatement $stmt
     * @return AlaniaContenidosModel[]
     */
    public static function fromExecutedStatement(PDOStatement $stmt) {
        $resultInstances = array();
        while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $o = new AlaniaContenidosModel();
            $o->assignByHash($result);
            $o->notifyPristine();
            $resultInstances[] = $o;
        }
        $stmt->closeCursor();
        return $resultInstances;
    }

    /**
     * Get sql WHERE part from filter.
     *
     * @param array $filter
     * @param bool $and
     * @param bool $fullyQualifiedNames true if field names should be qualified by table name
     * @param bool $prependWhere true if WHERE should be prepended to conditions
     * @return string
     */
    public static function buildSqlWhere($filter, $and, $fullyQualifiedNames = true, $prependWhere = false) {
        if (!($filter instanceof DFCInterface)) {
            $filter = new DFCAggregate($filter, $and);
        }
        return $filter->buildSqlWhere(new self::$CLASS_NAME, $fullyQualifiedNames, $prependWhere);
    }

    /**
     * get sql ORDER BY part from DSCs
     *
     * @param array $sort array of DSC instances
     * @return string
     */
    protected static function buildSqlOrderBy($sort) {
        return DSC::buildSqlOrderBy(new self::$CLASS_NAME, $sort);
    }

    /**
     * bind values from filter to statement
     *
     * @param PDOStatement $stmt
     * @param DFCInterface $filter
     */
    public static function bindValuesForFilter(PDOStatement &$stmt, DFCInterface $filter) {
        $filter->bindValuesForFilter(new self::$CLASS_NAME, $stmt);
    }

    /**
     * Execute select query and return matched rows as an array of AlaniaContenidosModel instances.
     *
     * The query should of course be on the table for this entity class and return all fields.
     *
     * @param PDO $db a PDO Database instance
     * @param string $sql
     * @return AlaniaContenidosModel[]
     */
    public static function findBySql(PDO $db, $sql) {
        $stmt = $db->query($sql);
        return self::fromExecutedStatement($stmt);
    }

    /**
     * Delete rows matching the filter
     *
     * The filter can be either an hash with the field id as index and the value as filter value,
     * or a array of DFC instances.
     *
     * @param PDO $db
     * @param array $filter
     * @param bool $and
     * @return mixed
     */
    public static function deleteByFilter(PDO $db, $filter, $and = true) {
        if (!($filter instanceof DFCInterface)) {
            $filter = new DFCAggregate($filter, $and);
        }
        if (0 == count($filter)) {
            throw new InvalidArgumentException('refusing to delete without filter'); // just comment out this line if you are brave
        }
        $sql = 'DELETE FROM `alania_contenidos`'
                . self::buildSqlWhere($filter, $and, false, true);
        $stmt = self::prepareStatement($db, $sql);
        self::bindValuesForFilter($stmt, $filter);
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        $stmt->closeCursor();
        return $affected;
    }

    /**
     * Assign values from array with the field id as index and the value as value
     *
     * @param array $array
     */
    public function assignByArray($array) {
        $result = array();
        foreach ($array as $fieldId => $value) {
            $result[self::$FIELD_NAMES[$fieldId]] = $value;
        }
        $this->assignByHash($result);
    }

    /**
     * Assign values from hash where the indexes match the tables field names
     *
     * @param array $result
     */
    public function assignByHash($result) {
        $this->setId($result['id']);
        $this->setNombre($result['nombre']);
        $this->setPlantilla($result['plantilla']);
        $this->setAlaniaTipoInformacionIdTipoInformacion($result['alania_tipo_informacion_id_tipo_informacion']);
        $this->setFechaCreacion($result['fecha_creacion']);
        $this->setFechaModificacion($result['fecha_modificacion']);
    }

    /**
     * Get element instance by it's primary key(s).
     * Will return null if no row was matched.
     *
     * @param PDO $db
     * @return AlaniaContenidosModel
     */
    public static function findById(PDO $db, $id) {
        $stmt = self::prepareStatement($db, self::SQL_SELECT_PK);
        $stmt->bindValue(1, $id);
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $stmt->closeCursor();
        if (!$result) {
            return null;
        }
        $o = new AlaniaContenidosModel();
        $o->assignByHash($result);
        $o->notifyPristine();
        return $o;
    }

    public static function findByName(PDO $db, $id) {
        $stmt = self::prepareStatement($db, self::SQL_SELECT_NAME);
        $stmt->bindValue(1, $id);
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $stmt->closeCursor();
        if (!$result) {
            return null;
        }
        $o = new AlaniaContenidosModel();
        $o->assignByHash($result);
        $o->notifyPristine();
        return $o;
    }

    /**
     * Bind all values to statement
     *
     * @param PDOStatement $stmt
     */
    protected function bindValues(PDOStatement &$stmt) {
        $stmt->bindValue(1, $this->getId());
        $stmt->bindValue(2, $this->getNombre());
        $stmt->bindValue(3, $this->getPlantilla());
        $stmt->bindValue(4, $this->getAlaniaTipoInformacionIdTipoInformacion());
        $stmt->bindValue(5, $this->getFechaCreacion());
        $stmt->bindValue(6, $this->getFechaModificacion());
    }

    /**
     * Insert this instance into the database
     *
     * @param PDO $db
     * @return mixed
     */
    public function insertIntoDatabase(PDO $db) {
        if (null === $this->getId()) {
            $stmt = self::prepareStatement($db, self::SQL_INSERT_AUTOINCREMENT);
            $stmt->bindValue(1, $this->getNombre());
            $stmt->bindValue(2, $this->getPlantilla());
            $stmt->bindValue(3, $this->getAlaniaTipoInformacionIdTipoInformacion());
            $stmt->bindValue(4, $this->getFechaCreacion());
            $stmt->bindValue(5, $this->getFechaModificacion());
        } else {
            $stmt = self::prepareStatement($db, self::SQL_INSERT);
            $this->bindValues($stmt);
        }
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        $lastInsertId = $db->lastInsertId();
        if (false !== $lastInsertId) {
            $this->setId($lastInsertId);
        }
        $stmt->closeCursor();
        $this->notifyPristine();
        return $affected;
    }

    /**
     * Update this instance into the database
     *
     * @param PDO $db
     * @return mixed
     */
    public function updateToDatabase(PDO $db) {
        $stmt = self::prepareStatement($db, self::SQL_UPDATE);
        $this->bindValues($stmt);
        $stmt->bindValue(7, $this->getId());
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        $stmt->closeCursor();
        $firephp=  FirePHP::getInstance(true);
        $firephp->log($this->getOldInstance());
        $this->notifyPristine();
        return $affected;
    }

    /**
     * Delete this instance from the database
     *
     * @param PDO $db
     * @return mixed
     */
    public function deleteFromDatabase(PDO $db) {
        $stmt = self::prepareStatement($db, self::SQL_DELETE_PK);
        $stmt->bindValue(1, $this->getId());
        $affected = $stmt->execute();
        if (false === $affected) {
            $stmt->closeCursor();
            throw new Exception($stmt->errorCode() . ':' . var_export($stmt->errorInfo(), true), 0);
        }
        $stmt->closeCursor();
        return $affected;
    }

    /**
     * Fetch AlaniaInformacionModel's which this AlaniaContenidosModel references.
     * `alania_contenidos`.`id` -> `alania_informacion`.`tipo_contenido`
     *
     * @param PDO $db a PDO Database instance
     * @param array $sort array of DSC instances
     * @return AlaniaInformacionModel[]
     */
    public function fetchAlaniaInformacionModelCollection(PDO $db, $sort = null) {
        $filter = array(AlaniaInformacionModel::FIELD_TIPO_CONTENIDO => $this->getId());
        return AlaniaInformacionModel::findByFilter($db, $filter, true, $sort);
    }

    /**
     * Fetch PermisosModel's which this AlaniaContenidosModel references.
     * `alania_contenidos`.`id` -> `permisos`.`alania_contenidos_id`
     *
     * @param PDO $db a PDO Database instance
     * @param array $sort array of DSC instances
     * @return PermisosModel[]
     */
    public function fetchPermisosModelCollection(PDO $db, $sort = null) {
        $filter = array(PermisosModel::FIELD_ALANIA_CONTENIDOS_ID => $this->getId());
        return PermisosModel::findByFilter($db, $filter, true, $sort);
    }

    /**
     * Fetch AlaniaTipoInformacionModel which references this AlaniaContenidosModel. Will return null in case reference is invalid.
     * `alania_contenidos`.`alania_tipo_informacion_id_tipo_informacion` -> `alania_tipo_informacion`.`id_tipo_informacion`
     *
     * @param PDO $db a PDO Database instance
     * @param array $sort array of DSC instances
     * @return AlaniaTipoInformacionModel
     */
    public function fetchAlaniaTipoInformacionModel(PDO $db, $sort = null) {
        $filter = array(AlaniaTipoInformacionModel::FIELD_ID_TIPO_INFORMACION => $this->getAlaniaTipoInformacionIdTipoInformacion());
        $result = AlaniaTipoInformacionModel::findByFilter($db, $filter, true, $sort);
        return empty($result) ? null : $result[0];
    }

    /**
     * return array with the property name as index and the field value as value.
     * ezComponents support method
     *
     * @return array
     */
    public function getState() {
        $array = $this->toArray();
        $state = array();
        foreach ($array as $fieldId => $value) {
            $state[self::$PROPERTY_NAMES[$fieldId]] = $value;
        }
        return $state;
    }

    /**
     * Assign values from hash where the indexes match the property names.
     * ezComponents support method
     *
     * @param array $state
     */
    public function setState(array $state) {
        $propertyNameToFieldId = array_flip(self::$PROPERTY_NAMES);
        $hash = $this->toHash();
        foreach ($state as $propertyName => $value) {
            $hash[self::$FIELD_NAMES[$propertyNameToFieldId[$propertyName]]] = $value;
        }
        $this->assignByHash($hash);
    }

    /**
     * get persistence definition for ezComponents
     *
     * @return ezcPersistentObjectDefinition
     */
    public static function toEzcPersistentObjectDefinition() {
        static $typeMapping = array(
    Db2PhpEntity::PHP_TYPE_BOOL => ezcPersistentObjectProperty::PHP_TYPE_BOOL,
    Db2PhpEntity::PHP_TYPE_INT => ezcPersistentObjectProperty::PHP_TYPE_INT,
    Db2PhpEntity::PHP_TYPE_FLOAT => ezcPersistentObjectProperty::PHP_TYPE_FLOAT,
    Db2PhpEntity::PHP_TYPE_STRING => ezcPersistentObjectProperty::PHP_TYPE_STRING
        );
        $def = new ezcPersistentObjectDefinition();
        $def->table = self::SQL_TABLE_NAME;
        $def->class = 'AlaniaContenidosModel';
        if (!empty(self::$PRIMARY_KEYS)) {
            $pkField = self::$PRIMARY_KEYS[0];
            $def->idProperty = new ezcPersistentObjectIdProperty();
            $def->idProperty->columnName = self::$FIELD_NAMES[$pkField];
            $def->idProperty->propertyName = self::$PROPERTY_NAMES[$pkField];
            $def->idProperty->generator = new ezcPersistentGeneratorDefinition(
                    in_array($pkField, self::$AUTOINCREMENT_FIELDS) ? 'ezcPersistentNativeGenerator' : 'ezcPersistentManualGenerator');
        } else {
            $pkField = null;
        }
        foreach (self::$PROPERTY_NAMES as $fieldId => $propertyName) {
            if ($fieldId !== $pkField) {
                $def->properties[$propertyName] = new ezcPersistentObjectProperty();
                $def->properties[$propertyName]->columnName = self::$FIELD_NAMES[$fieldId];
                $def->properties[$propertyName]->propertyName = $propertyName;
                $def->properties[$propertyName]->propertyType = $typeMapping[self::$PROPERTY_TYPES[$fieldId]];
            }
        }
        return $def;
    }

    /**
     * get element as DOM Document
     *
     * @return DOMDocument
     */
    public function toDOM() {
        return self::hashToDomDocument($this->toHash(), 'AlaniaContenidosModel');
    }

    /**
     * get single AlaniaContenidosModel instance from a DOMElement
     *
     * @param DOMElement $node
     * @return AlaniaContenidosModel
     */
    public static function fromDOMElement(DOMElement $node) {
        $o = new AlaniaContenidosModel();
        $o->assignByHash(self::domNodeToHash($node, self::$FIELD_NAMES, self::$DEFAULT_VALUES, self::$FIELD_TYPES));
        $o->notifyPristine();
        return $o;
    }

    /**
     * get all instances of AlaniaContenidosModel from the passed DOMDocument
     *
     * @param DOMDocument $doc
     * @return AlaniaContenidosModel[]
     */
    public static function fromDOMDocument(DOMDocument $doc) {
        $instances = array();
        foreach ($doc->getElementsByTagName('AlaniaContenidosModel') as $node) {
            $instances[] = self::fromDOMElement($node);
        }
        return $instances;
    }

}

?>